/**
 * 
 */
package info.niwota.install.web;

import info.niwota.commons.web.AjaxRegistry;
import info.niwota.commons.web.PageCursor;
import info.niwota.install.Debug;
import info.niwota.webapp.web.PageContentProvider;

import org.json.JSONObject;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.util.Log;

/**
 * @author qiangli
 *
 */
public class InstallPageContentProvider extends PageContentProvider {
	private static final String TAG = "InstallPageContentProvider";

	@Override
	public boolean onCreate() {
		super.onCreate();
		//
		registerObjects();

		return true;
	}

	private void registerObjects() {
		final Context ctx = getContext();
		AjaxRegistry.getInstance()
				.add(InstallObject.NAME, new InstallObject(ctx));
	}

	@Override
	protected void showMainPage(PageCursor c, Uri uri, int group, String user,
			String path) throws Exception {
		final String label = Label.LABEL;
		checkAccess(uri, group, user, label);

		JSONObject data = new JSONObject();
		String peer = uri.getQueryParameter("peer");
		data.put("peer", NVL(peer, ""));

		handleAssetData(c, "main.tpl", TEXT_HTML, data);
	}

	@Override
	protected boolean showContent(PageCursor c, Uri uri, int group,
			String user, String path) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "showContent path: " + path + " uri: " + uri);
		}

		//html pages
		if (path.startsWith("/") && path.endsWith(".htm")) {
			handleAsset(c, path.substring(1), "text/html");
			return true;
		}

		// only one label for now
		final String label = Label.LABEL;

		checkAccess(uri, group, user, label);

		//
		throw new NotFoundException(uri.toString());
	}
}
